package com.qq.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    //这里的方法被dologin给调用了
    //这里是将连接数据库的语句
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://127.0.0.1:3306/library?characterEncoding=utf-8";
    private static String user = "root";
    private static String password = "123456";
    private static Connection con;
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //这里写构造方法了在其他地方就不能new对象了比如在TTT类里面
   private DBUtil(){}

    public static Connection getConnection(){
//        try {
//            Class.forName("com.mysql.jdbc.Driver");
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }

       // Connection con = null;
//实现单例，为来了防止创建多个对象
        try{
            if (con ==null){

                    con = DriverManager.getConnection(url,user,password);
                    return con;
                }else {
                //判断是否关闭，关闭就重新连接
                if (con.isClosed()){
                    con = DriverManager.getConnection(url,user,password);
                    return con;
                }else {
                    return con;
                }
            }
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }
}
